package com.example.seh.home.select;


import android.content.Context;

import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;

import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import androidx.annotation.NonNull;

import com.example.seh.R;
import com.example.seh.constant.Constant;
import com.example.seh.home.secondhand.GoodsDTO;
import com.example.seh.square.Post;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;


public class SearchView extends LinearLayout implements View.OnClickListener {

    /**
     * 输入框
     */
    public EditText etInput;

    /**
     * 搜索键键
     */
    private ImageView select;


    /**
     * 上下文对象
     */
    private Context mContext;

    /**
     * 弹出列表
     */
    private ListView lvTips;

    /**
     * 提示adapter （推荐adapter）
     */
    private ArrayAdapter<String> mHintAdapter;

    /**
     * 自动补全adapter 只显示名字
     */
    private ArrayAdapter<String> mAutoCompleteAdapter;

    /**
     * 搜索回调接口
     */
    private SearchViewListener mListener;

    private List<Bean> dbData = new ArrayList<>();
    private List<GoodsDTO> goodsDTOS = new ArrayList<>();

    private DataLoadedCallback dataLoadedCallback;

    private boolean isDataLoaded = false;
    private Handler myHandler = new Handler(Looper.myLooper()) {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    if (mAutoCompleteAdapter != null && lvTips.getAdapter() != mAutoCompleteAdapter) {
                        lvTips.setAdapter(mAutoCompleteAdapter);
                    }
                    break;
            }
        }
    };

    private Handler mainHandler = new Handler(Looper.getMainLooper());


    /**
     * 设置搜索回调接口
     *
     * @param listener 监听者
     */
    public void setSearchViewListener(SearchViewListener listener) {
        mListener = listener;
    }

    public SearchView(Context context, AttributeSet attrs) {
        super(context, attrs);
        mContext = context;
        LayoutInflater.from(context).inflate(R.layout.search_layout, this);
        initViews();
    }

    private void initViews() {
        etInput = findViewById(R.id.search_et_input);
        select = findViewById(R.id.search_iv_select);

        lvTips = findViewById(R.id.search_lv_tips);



        select.setOnClickListener(this);
        onItemClick();
        etInput.addTextChangedListener(new EditChangedListener());
        etInput.setOnClickListener(this);
        etInput.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView textView, int actionId, KeyEvent keyEvent) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    lvTips.setVisibility(GONE);
                    notifyStartSearching(etInput.getText().toString());
                }
                return true;
            }
        });

        // 创建一个实现了DataLoadedCallback接口的对象
        DataLoadedCallback callback = new DataLoadedCallback() {
            @Override
            public void onDataLoaded(List<Bean> data) {
                // 在这里处理dbData数据，例如更新UI或执行其他操作
                Log.e("Data Loaded", "Data: " + data.toString());

                // 例如，更新自动完成适配器
                if (mListener != null) {
                    mListener.onRefreshAutoComplete(etInput.getText().toString(), data);
                }

            }
        };

        // 设置回调对象
        setDataLoadedCallback(callback);
    }
    private void onItemClick(){
        lvTips.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {

                // 数据加载完成后执行的逻辑
                String text = lvTips.getAdapter().getItem(i).toString();
                etInput.setText(text);
                etInput.setSelection(text.length());
                lvTips.setVisibility(View.GONE);

                mainHandler.post(new Runnable() {
                    @Override
                    public void run() {
                        notifyStartSearching(text);
                    }
                });
            }
        });
    }

    /**
     * 通知监听者 进行搜索操作
     *
     * @param text
     */
    private void notifyStartSearching(String text) {
        if (mListener != null) {
            mListener.onSearch(etInput.getText().toString(), dbData);
            Log.e("onsearch", dbData.toString());
            Log.e("text", text);
        }
        //隐藏软键盘
        InputMethodManager imm = (InputMethodManager) mContext.getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
    }

    /**
     * 设置热搜版提示 adapter
     */
    public void setTipsHintAdapter(ArrayAdapter<String> adapter) {
        this.mHintAdapter = adapter;
        if (lvTips.getAdapter() == null) {
            lvTips.setAdapter(mHintAdapter);
        }
    }

    /**
     * 设置自动补全adapter
     */
    public void setAutoCompleteAdapter(ArrayAdapter<String> adapter) {
        this.mAutoCompleteAdapter = adapter;
    }

    private class EditChangedListener implements TextWatcher {
        @Override
        public void beforeTextChanged(CharSequence charSequence, int i, int i2, int i3) {

        }

        @Override
        public void onTextChanged(CharSequence charSequence, int i, int i2, int i3) {
            if (!"".equals(charSequence.toString())) {
                select.setVisibility(VISIBLE);
                lvTips.setVisibility(VISIBLE);
                String text = charSequence.toString();
                dbData.clear();
                sendData(text);

            } else {
                select.setVisibility(GONE);
                if (mHintAdapter != null) {
                    lvTips.setAdapter(mHintAdapter);
                }
                lvTips.setVisibility(GONE);
            }
        }


        @Override
        public void afterTextChanged(Editable editable) {

        }
    }

    private void sendData(String text) {
        OkHttpClient okHttpClient = new OkHttpClient();

        Request request = new Request.Builder()
                .url(Constant.SEARCH_SEND + "key=" + text)
                .get()
                .build();
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.e("OkHttp", "发送失败");
                e.printStackTrace();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String responseData = response.body().string();
                Log.e("responseData", responseData);
                getDataFromJsonData(responseData);
                // 数据加载完毕后，调用回调方法传递数据
                if (dataLoadedCallback != null) {
                    dataLoadedCallback.onDataLoaded(dbData);
                }
            }
        });

    }

    public void getDataFromJsonData(String selectData) {
        try {
            JSONObject jsonObject = new JSONObject(selectData);
            //String selectDataStr = jsonObject.getString("data");
            String selectDataStr = jsonObject.getString("searchHits");

            JSONArray jsonArray = new JSONArray(selectDataStr);
            for (int i = 0; i < jsonArray.length(); i++) {
                JSONObject json = (JSONObject) jsonArray.get(i);
                JSONObject content = json.getJSONObject("content");
                String[] goodsPicStr = content.getString("goodsPic").split(";");
                Bean bean = new Bean();
                if (goodsPicStr.length > 0 && goodsPicStr[0] != null) {
                    bean.setIconId(goodsPicStr[0]);
                }
                bean.setGoodsPic(content.getString("goodsPic"));
                bean.setTitle(content.getString("goodsName"));
                bean.setContent(content.getString("goodsDesc"));
                bean.setCategory(content.getString("goodsCategory"));
                bean.setGoodsId(Integer.valueOf(content.getString("id")));
                bean.setPrice(Double.valueOf(content.getString("goodsPrice")));
                dbData.add(bean);

            }
            Log.e("dbData", dbData.toString());

            mainHandler.post(new Runnable() {
                @Override
                public void run() {
                    mAutoCompleteAdapter.notifyDataSetChanged();
                }
            });

        } catch (JSONException e) {
            e.printStackTrace();
        }
        Message message = new Message();
        message.what = 1;
        myHandler.sendMessage(message);
    }


    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.search_et_input:
                lvTips.setVisibility(VISIBLE);
                break;
            case R.id.search_iv_select:
                lvTips.setVisibility(View.GONE);
                notifyStartSearching(etInput.getText().toString());
                break;
        }
    }

    public interface DataLoadedCallback {
        void onDataLoaded(List<Bean> data);
    }

    // 在合适的地方设置回调对象
    public void setDataLoadedCallback(DataLoadedCallback callback) {
        this.dataLoadedCallback = callback;
    }

    /**
     * search view回调方法
     */
    public interface SearchViewListener {

        /**
         * 更新自动补全内容
         *
         * @param text 传入补全后的文本
         */
        void onRefreshAutoComplete(String text, List<Bean> beans);

        /**
         * 开始搜索
         *
         * @param text 传入输入框的文本
         */
        void onSearch(String text, List<Bean> beans);

        //        /**
//         * 提示列表项点击时回调方法 (提示/自动补全)
//         */
        void onTipsItemClick(String text);


    }

}



